package com.ruoyi.api.web;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.shop.service.IShopPaymentRecordService;
import com.ruoyi.shop.service.IShopUserOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author Alan Zhang
 * @Date 2021/9/25 13:33
 */
@Api(tags = "支付回调接口")
@RestController
@RequestMapping("/api/wechat/pay")
public class ApiWxPayNoticeController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 小程序支付
     */
    @Autowired
    private WxPayService wxService;
    @Autowired
    private IShopPaymentRecordService shopPaymentRecordService;

    @ApiOperation(value = "支付回调通知处理")
    @PostMapping("/notify/order")
    public String parseOrderNotifyResult(@RequestBody String xmlData) throws WxPayException {
        final WxPayOrderNotifyResult notifyResult = this.wxService.parseOrderNotifyResult(xmlData);
        // TODO 根据自己业务场景需要构造返回对象
        logger.info(xmlData);
        logger.info(notifyResult.toString());

        if(WxPayConstants.ResultCode.SUCCESS.equals(notifyResult.getResultCode())) {
            // 根据内部订单号更新order settlement
            shopPaymentRecordService.paySuccess(notifyResult);
        } else {
            shopPaymentRecordService.payFail(notifyResult);
        }
        return WxPayNotifyResponse.success("成功");
    }


    @ApiOperation(value = "退款回调通知处理")
    @PostMapping("/notify/refund")
    public String parseRefundNotifyResult(@RequestBody String xmlData) throws WxPayException {
        logger.info(xmlData);

        final WxPayRefundNotifyResult result = this.wxService.parseRefundNotifyResult(xmlData);

        logger.info(result.toString());
        // TODO 根据自己业务场景需要构造返回对象
        return WxPayNotifyResponse.success("成功");
    }
}
